package com.note7_6;

import java.io.*;
import java.util.Scanner;

public class Question3 {

	/*
	 * 
	 * 3：实现文件加密解密：加密规则是读出每一个字节，取反(~)后，写入新文件
	 * 然后删除原文件，把新文件改成原文件同名的文件，
	 * 解密规则类似。输入一个文件名，实现加密和解密功能
	 */
	
	public static String reName(String name){
		String newName = name.substring(0, name.lastIndexOf(".")) + "1";
		String lastName = name.substring(name.lastIndexOf("."));
		newName = newName + lastName;
		return newName;
	}
	
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		System.out.println("请输入要进行加密或解密的文件位置：");
		String path = in.nextLine();
		//D:/myeclipse/workpace/com/src/com/question.txt
		File f = new File(path);
		String name = reName(f.getName());
		File f1 = new File(name);
		DataInputStream dis = null;
		DataOutputStream dos = null;
		try {
			dis = new DataInputStream(new FileInputStream(f));
			dos = new DataOutputStream(new FileOutputStream(f1));
			byte[] bs = new byte[dis.available()];
			while((dis.read(bs)) != -1){
				for(byte b:bs){
					int b1 = ~b;
					dos.write(b1);
				}
			}
			dis.close();
			dos.close();
			f.delete();
			if(f1.renameTo(f)){
				System.out.println("转换成功");
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(dis != null){
				try {
					dis.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(dos != null){
				try {
					dos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}
